use actix_web::{dev::Service, http::StatusCode, web, App, HttpResponse, HttpServer};

mod controllers;

#[actix_web::main]
pub async fn start() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .wrap_fn(|req, srv| {
                if let Some(header) = req.headers().get("authorization") {
                    println!("Header: {:?}", header);
                }

                let path = req.uri().path().to_string();
                let fut = srv.call(req);

                async move {
                    let res = fut.await?;

                    if controllers::interceptor::check_access_permission() {
                        Ok(res)
                    } else {
                        Ok(res.into_response(HttpResponse::Unauthorized().json(
                            controllers::shared::get_error_response_data(
                                StatusCode::UNAUTHORIZED,
                                "UNAUTHORIZED",
                                "Error Code Value",
                                &path,
                            ),
                        )))
                    }
                }
            })
            .app_data(web::JsonConfig::default().limit(10 * 1024 * 1024)) // 10 MB limit
            .service(web::scope("family-expense-api").configure(controllers::routing::set_routes))
    })
    .bind(("127.0.0.1", 8088))?
    .run()
    .await
}
